#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2020/8/19 14:30
# @Author  : ystraw
# @Site    : 
# @File    : dealword_1.py
# @Software: PyCharm Community Edition
# @function: 将有道导入的单词整理成规范格式
import re

def readFile(path):
    print('正在读取：', path)
    with open(path, 'r+', encoding='utf-8') as f:
        string = f.read()
    print('读取完成！', path)
    return string

def writeFile(path, content):
    print('正在写入：', path)
    with open(path, 'w+', encoding='utf-8') as f:
        f.write(content)
    print('写入完成！', path)

if __name__ == '__main__':
    # 需要整理的文件
    pathfile = './word/有道导出格式/yd_words.txt'
    # 保存数据文件
    newfile = './word/yd_word_1.txt'
    # 读取数据
    oldfile = readFile(pathfile)
    # 提取单词
    # matchObj = re.match(r'([0-9]+,) ([a-zA-Z]+)', oldfile)
    p = re.compile(r'([0-9]+,) ([a-zA-Z\.]+)')  # 构建匹配格式
    wordList = p.findall(oldfile)  # 返回所有匹配结果
    print(wordList)
    # 替换单词编号
    # oldfile = re.sub(r'([0-9]+,)', "##", oldfile)
    # print(oldfile[:200])
    wordstr = ''
    unit = 1
    # 写入文件的路径
    path = './word/插入数据库格式/unit%d.txt'
    for i in range(len(wordList)):
        if i > 0 and i % 30 == 0:
            writeFile(path % unit, wordstr)
            unit += 1
            wordstr = ''
        wordstr += wordList[i][1] + '\n'
    if wordstr != '':
        writeFile(path % unit, wordstr)

